package tema1.weather;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

class Localitate
{
	public String nume;

	@Override
	public String toString ()
	{
		return nume;
	} 
}

class LocalitatiAdapter extends BaseAdapter
{
	private Activity context;
	ArrayList<Localitate> localitati;

	public int delLocalitate(Localitate localitate)
	{
		localitati.remove(localitate);
		this.notifyDataSetChanged();
		return 0;
	}

	public LocalitatiAdapter (Activity _context)
	{
		this.context = _context;
		localitati = new ArrayList<Localitate>();
	}

	public View getView (int position, View convertView, ViewGroup list) 
	{
		View element;
		if (convertView == null)
		{
			LayoutInflater inflater = context.getLayoutInflater();
			element = inflater.inflate(R.layout.localitate, null);
		}
		else element = convertView;

		TextView nume = (TextView)element.findViewById(R.id.localitate_nume);

		nume.setText(localitati.get(position).nume);

		return element;
	}

	public int getCount()
	{
		return localitati.size ();
	}

	public Object getItem(int position) 
	{
		return localitati.get(position);
	}

	public long getItemId(int position) 
	{
		return 0;
	}

	public void adaugaOras (String nume)
	{
		Localitate p = new Localitate ();
		p.nume = nume;
		localitati.add (p);
		this.notifyDataSetChanged();
	}

	public Object getText() {
		return localitati.toArray();
	}

}

public class WeatherActivity extends ListActivity
{
	LocalitatiAdapter adapter;
	Button button;
	private final static String NOTES="loc.txt";
	public int back=0;
	public static String[] data=new String[30];
	ProgressDialog progressDialog;

	public void showProgressDialog() { 
		progressDialog = new ProgressDialog(WeatherActivity.this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("Loading! Please wait...");
		progressDialog.show();
	}

	private void dismissProgressDialog() {
		if(progressDialog != null)
			progressDialog.dismiss();
	}

	@Override
	public void onCreate (Bundle savedInstanceBundle)
	{
		super.onCreate (savedInstanceBundle);
		adapter = new LocalitatiAdapter (this);
		setContentView (R.layout.main);
		setListAdapter (adapter);

		final AlertDialog alert = new AlertDialog.Builder(this).create();
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setTitle("Add New City");
		alert.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				Toast.makeText(getApplicationContext(), value,
						Toast.LENGTH_SHORT).show();
				try {
					URL url = new URL("http://www.google.com/ig/api?weather="+input.getText().toString());
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();
					Document doc = db.parse(new InputSource(url.openStream()));

					NodeList nodeList = doc.getElementsByTagName("forecast_information");
					if(nodeList.getLength()>0){
						if(adapter.isEmpty()){
							adapter.adaugaOras(input.getText().toString());
							try {
								OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, MODE_APPEND));
								out.write(input.getText().toString()+"\n");
								out.flush();
								out.close();
							} catch (Throwable t) {}
						}
						else{
							for(int m=0;m<adapter.getCount();m++){
								if(input.getText().toString().equalsIgnoreCase(adapter.getItem(m).toString())){
									Toast.makeText(getApplicationContext(), "City already exist !",Toast.LENGTH_SHORT).show();
									break;
								}else{
									if(m==adapter.getCount()-1){
										adapter.adaugaOras(input.getText().toString());
										try {
											OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, MODE_APPEND));
											out.write(input.getText().toString()+"\n");
											out.flush();
											out.close();
										} catch (Throwable t) {}
										break;
									}
								}
							}
						}

						input.setText("");
					}else{
						Toast.makeText(getApplicationContext(), "City not found !",Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					System.out.println("XML Pasing Excpetion = " + e);
				}
			}
		});

		alert.setButton2("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});


		button = (Button) findViewById(R.id.buton);
		button.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				alert.show();

			}
		});



		getListView().setOnItemLongClickListener(new OnItemLongClickListener() 
		{


			public boolean onItemLongClick(AdapterView<?> listAdapter, View view,
					int position, long id) 
			{
				Localitate p = (Localitate)adapter.getItem (position);
				try {
					OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES,MODE_WORLD_WRITEABLE));
					out.write("");
					out.close();
				} catch (Throwable t) {

				}
				adapter.delLocalitate(p);
				for(int i=0;i<adapter.getCount();i++){
					try {
						OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, MODE_APPEND));
						out.write(adapter.getItem(i)+"\n");
						out.flush();
						out.close();
					} catch (Throwable t) {

					}
				}
				return true;
			}
		});


	}

	public void onResume() {
		super.onResume();
		dismissProgressDialog();
		if(back==0){
			try {
				InputStream in = openFileInput(NOTES);
				if (in != null) {
					InputStreamReader tmp = new InputStreamReader(in);
					BufferedReader reader = new BufferedReader(tmp);
					String str;

					while ((str = reader.readLine()) != null) {
						adapter.adaugaOras(str);
					}
					in.close();
					back=1;
				}
			} catch (java.io.FileNotFoundException e) {
			} catch (Throwable t) {
				Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
			}
		}
	}

	@Override
	public void onListItemClick (ListView list, View v, int position, long id)
	{
		try{
			showProgressDialog();
		}catch(Exception e){}
		vreme vr=new vreme();
		Localitate p = (Localitate)adapter.getItem (position);
		Toast.makeText(this, p.nume, Toast.LENGTH_LONG).show();
		vr.oras(p.nume);
		vr.info_v("forecast_information","forecast_date",0);
		vr.info_v("current_conditions","condition",1);
		vr.info_v("current_conditions","temp_c",2);
		vr.info_v("current_conditions","humidity",3);
		vr.info_v("current_conditions","icon",4);
		vr.info_v("current_conditions","wind_condition",5);	
		vr.info_v("forecast_conditions","day_of_week",6);
		vr.info_v("forecast_conditions","low",10);
		vr.info_v("forecast_conditions","icon",14);
		vr.info_v("forecast_conditions","condition",18);

		Intent intent = new Intent();
		intent.setClass(WeatherActivity.this, Info.class);
		for(int i=0;i<30;i++)
			intent.putExtra("c"+i, data[i]);
		startActivity(intent);
	}


	class vreme{

		public Document doc;

		public void oras(String s){
			try {

				URL url = new URL("http://www.google.com/ig/api?weather="+s);
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				doc = db.parse(new InputSource(url.openStream()));
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
		}

		public void info_v(String s1,String s2,int j){

			NodeList nodeList = doc.getElementsByTagName(s1);
			for (int i = 0; i < nodeList.getLength(); i++)
			{
				Element currentConditionsElement = (Element) nodeList.item(i);
				NodeList conditionList = currentConditionsElement.getElementsByTagName(s2);
				Element conditionElement = (Element) conditionList.item(0);
				String dataAttribute = conditionElement.getAttribute("data");
				data[j]=dataAttribute;
				if(nodeList.getLength()>1){
					j++;
				}
			}

		}

	}

}

